package zj.it.bhne.image;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.GeneralParams;
import com.baidu.ocr.sdk.model.GeneralResult;
import com.baidu.ocr.sdk.model.Word;
import com.baidu.ocr.sdk.model.WordSimple;
import com.github.chrisbanes.photoview.PhotoView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_CAMERA = 1000;
    private static final int REQUEST_CODE_PICK_IMAGE = 2000;
    private PhotoView ocr_im;
    public static String path;
    public static Bitmap bitmap;
    private Context context;
    private File mImageFile;
    private Uri mImageUri;
    private String mImageName;
    private String mImagePath;
    private Button shibie;

    /**
     * 壓縮Bitmap
     */
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        //获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        //计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        //取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        //得到新的图片
        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ResultActivity.resultBitmap!=null){
            ocr_im.setImageBitmap(ResultActivity.resultBitmap);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        initView();
        checkPermission();
    }

    private void initView() {
        Button ocr_btn = findViewById(R.id.ocr_btn);
        ocr_im = findViewById(R.id.ocr_im);

        ocr_btn.setOnClickListener(this);
        Button ocr_camera = findViewById(R.id.ocr_camera);
        ocr_camera.setOnClickListener(this);
        shibie = (Button) findViewById(R.id.shibie);
        shibie.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ocr_btn:
                //调取相册
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    int ret = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission
                            .READ_EXTERNAL_STORAGE);
                    if (ret != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                1000);
                        return;
                    }
                }
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                break;
            case R.id.ocr_camera:

                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //未获得，向用户请求
                    Log.d("TAG", "无读写权限，开始请求权限。");
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]
                            {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
                } else {
                    Log.d("TAG", "有读写权限，准备启动相机。");
                    //启动照相机
                    startCamera();
                }
                break;
            case R.id.shibie:
                if (ResultActivity.resultBitmap!=null){
                    initData();
                }else
                    Toast.makeText(context, "图片为空", Toast.LENGTH_SHORT).show();
                break;
        }
    }


    /**
     * 返回用户是否允许权限的结果，并处理
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResult) {
        if (requestCode == 200) {
            //用户允许权限
            if (grantResult[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("TAG", "用户已允许权限，准备启动相机。");
                //启动照相机
                startCamera();
            } else {  //用户拒绝
                Log.d("TAG", "用户已拒绝权限，程序终止。");
                Toast.makeText(this, "程序需要写入权限才能运行", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void startCamera() {
        //调取相机
        Intent intents = new Intent();
        intents.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intents.addCategory(Intent.CATEGORY_DEFAULT);
        createImageFile();
        intents.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //做一些处理
            //获取uri
            mImageUri = FileProvider.getUriForFile(this, "zj.it.bhne.gridengineeringsurvey.fileprovider", mImageFile);
        } else {
            //在版本低于此的时候，做一些处理
            mImageUri = Uri.fromFile(mImageFile);
        }

        intents.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        startActivityForResult(intents, REQUEST_CODE_CAMERA);
    }


    /**
     * 创建图片文件
     */
    private void createImageFile() {
        //设置图片文件名（含后缀），以当前时间的毫秒值为名称
        mImageName = Calendar.getInstance().getTimeInMillis() + ".jpg";
        //创建图片文件
        mImageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/aaa/", mImageName);
        //将图片的绝对路径设置给mImagePath，后面会用到
        mImagePath = mImageFile.getAbsolutePath();
        //按设置好的目录层级创建
        mImageFile.getParentFile().mkdirs();
        //不加这句会报Read-only警告。且无法写入SD
        mImageFile.setWritable(true);

    }

    /**
     * 获取权限
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int ret = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
            if (ret == PackageManager.PERMISSION_DENIED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.READ_PHONE_STATE},
                        100);
            }
        }
    }

    /**
     * 方法回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //拍照的回调
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //更新系统图库
            updateSystemGallery();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            path = mImageUri.getPath();
            startActivity(new Intent(context,ResultActivity.class));
            //initData();
        }
        //相册选取
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            //获取选择照片的数据视图
            assert selectedImage != null;
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            //从数据视图中获取已选择图片的路径
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            path = picturePath;
            //ocr_im.setImageBitmap(zoomImg(BitmapFactory.decodeFile(picturePath), 360, 640));
            bitmap = BitmapFactory.decodeFile(picturePath);
            //initData();
            startActivity(new Intent(context,ResultActivity.class));
        }
    }

    /**
     * 更新系统图库
     */
    private void updateSystemGallery() {
        //把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    mImageFile.getAbsolutePath(), mImageName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + mImagePath)));
    }

    /**
     * 获取token
     */
    private void initData() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                //String token = result.getAccessToken();
                getData();
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                /*Looper.prepare();
                Toast.makeText(context, "AK，SK方式获取token失败" + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                Looper.loop();*/
                Log.e("TAG", "onError: " + error.getLocalizedMessage());
            }
        }, getApplicationContext(), "NupG9NOKVEeGY2qVBYtitral", "lzcTgbsYpE1YFGiRG5aNSGEfrt2eUUrj");
    }

    /**
     * 解析图片中的文字
     */
    private void getData() {
        GeneralParams param = new GeneralParams();
        param.setDetectDirection(true);
        param.setVertexesLocation(true);
        param.setRecognizeGranularity(GeneralParams.GRANULARITY_SMALL);
        param.setImageFile(new File(path));
        OCR.getInstance(context).recognizeAccurate(param, new OnResultListener<GeneralResult>() {
            @Override
            public void onResult(GeneralResult result) {
                StringBuilder sb = new StringBuilder();
                for (WordSimple wordSimple : result.getWordList()) {
                    Word word = (Word) wordSimple;
                    sb.append(word.getWords());
                    sb.append(" ");
                }
                //listener.onResult(result.getJsonRes());
                createDialog(sb.toString());
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onError(OCRError error) {
                //listener.onResult(error.getMessage());
                //ocr_tv.setText(error.getErrorCode() + "  " + error.getMessage());
                createDialog(error.getErrorCode() + "  " + error.getMessage());
            }
        });
    }

    private void createDialog(String result) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("OCR识别");
        TextView textView = new TextView(context);
        textView.setText(result);
        builder.setView(textView);
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }

}
